package com.junlong0716.enjoylearning.service

import android.content.Intent
import android.media.MediaPlayer
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.RememberPlayMusicEntity
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.realm.Realm
import java.util.concurrent.TimeUnit

/**
 *@author: EdsionLi
 *@description:
 *@date: Created in 2018/7/30 下午5:05
 *@modified by:
 */

class PlayerManager private constructor(musicService: MusicService) {
    private var mMediaPlayer: MediaPlayer? = null
    private var mMusicService = musicService
    private var mPlayMusicCallbackList: ArrayList<PlayMusicCallback> = ArrayList()
    private var mDisposable: Disposable? = null
    private var mPlayerBarVisibility = false
    private var mAudioEntity: AudioEntity? = null
    private var mRealm: Realm? = null
    private var rememberPlayMusic: RememberPlayMusicEntity? = null
    private var currentDuring: Int = 0
    private lateinit var commentPresenter: CommentPresenter

    companion object {
        @Volatile
        var instance: PlayerManager? = null

        //单例
        fun getInstance(musicService: MusicService): PlayerManager? {
            if (instance == null) {
                synchronized(PlayerManager::class) {
                    if (instance == null) {
                        instance = PlayerManager(musicService)
                    }
                }
            }
            return instance
        }
    }

    init {
        //实例化MediaPlayer
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer()
        }

        //实例化realm
        mRealm = Realm.getDefaultInstance()

        //是否循环播放
        mMediaPlayer!!.isLooping = false

        //音乐播放完成监听
        mMediaPlayer!!.setOnCompletionListener {

            //            try {
//                mRealm!!.executeTransaction { it ->
//                    val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", mAudioEntity!!.id).findFirst()
//                    if (rememberPlayMusicEntity != null) {
//                        rememberPlayMusicEntity.currentDuring = 0
//                    }
//                }
//            }catch (e:Exception){
//                Logger.e("未知错误")
//            }

            for (i in 0 until mPlayMusicCallbackList.size) {
                mPlayMusicCallbackList[i].onPlayMusicComplete()
            }

            //播放完成 停止记录

            if(mAudioEntity!=null){
                val intent = Intent(mMusicService, RecordStudyEndService::class.java)
                intent.putExtra("KNOWLEDGE_ID", mAudioEntity!!.id)
                mMusicService.startService(intent)
            }
        }

        //音乐缓冲完成
        mMediaPlayer!!.setOnPreparedListener {
            mMediaPlayer!!.start()

            //ToastUtils.showShort("缓冲完毕")

            for (i in 0 until mPlayMusicCallbackList.size) {
                mPlayMusicCallbackList[i].onPlayerMediaPrepared()
            }
        }

        //防止多次创建倒计时
        if (mDisposable != null && !mDisposable!!.isDisposed) {
            mDisposable!!.dispose()
        }

        //获取当前播放位置
        mDisposable = Observable.interval(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    for (i in 0 until mPlayMusicCallbackList.size) {
                        mPlayMusicCallbackList[i].onPlayerCurrentPosition(mMediaPlayer!!.currentPosition)
                    }
                }
    }

    //添加监听回调
    fun addListenerCallback(playMusicCallback: PlayMusicCallback) {
        mPlayMusicCallbackList.add(playMusicCallback)
    }

    //移除监听回调
    fun removeListenerCallback(playMusicCallback: PlayMusicCallback) {
        mPlayMusicCallbackList.remove(playMusicCallback)
    }

    //继续播放音乐
    fun playMusic() {
        mMediaPlayer!!.start()
        for (i in 0 until mPlayMusicCallbackList.size) {
            mPlayMusicCallbackList[i].onPlayerStart(false)
        }

        commentPresenter = CommentPresenter()
        commentPresenter.requestAddStudyTime(mMusicService, mAudioEntity!!.id, object : CommentPresenter.AddStudyTimeCallback {
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })
    }

    //播放一条音乐
    fun playMusic(audioEntity: AudioEntity) {

        if (mAudioEntity!=null){
            if (mAudioEntity!!.id != audioEntity.id){
                mRealm!!.executeTransaction { it ->
                    val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", mAudioEntity!!.id).findFirst()
                    if (rememberPlayMusicEntity != null) {
                        rememberPlayMusicEntity.currentDuring = mMediaPlayer!!.currentPosition
                    }
                }
            }
        }

        mAudioEntity = audioEntity
        rememberPlayMusic = mRealm!!.where(RememberPlayMusicEntity::class.java).equalTo("musicId", mAudioEntity!!.id).findFirst()
        mMediaPlayer!!.reset()
        mMediaPlayer!!.setDataSource(mAudioEntity!!.path)
        mMediaPlayer!!.prepareAsync()

        for (i in 0 until mPlayMusicCallbackList.size) {
            mPlayMusicCallbackList[i].onPlayerStart(true)
        }

        //音乐缓冲完成
        mMediaPlayer!!.setOnPreparedListener {
            mMediaPlayer!!.start()

            //ToastUtils.showShort("缓冲完毕")

            for (i in 0 until mPlayMusicCallbackList.size) {
                mPlayMusicCallbackList[i].onPlayerMediaPrepared()
            }
        }

        //先查询是否有该条数据 没有则新增
        if (rememberPlayMusic == null) {
            mRealm!!.executeTransaction { it ->
                val rememberPlayMusicEntity = RememberPlayMusicEntity()
                rememberPlayMusicEntity.musicId = mAudioEntity!!.id
                rememberPlayMusicEntity.currentDuring = 0
                it.copyToRealm(rememberPlayMusicEntity)
            }
        } else {
            //有的话 直接从记录的位置进行播放
            currentDuring = rememberPlayMusic!!.currentDuring!!

            mMediaPlayer!!.setOnPreparedListener {
                mMediaPlayer!!.start()
                mMediaPlayer!!.seekTo(currentDuring)

                for (i in 0 until mPlayMusicCallbackList.size) {
                    mPlayMusicCallbackList[i].onPlayerMediaPrepared()
                }
            }
        }

        commentPresenter = CommentPresenter()
        commentPresenter.requestAddStudyTime(mMusicService, mAudioEntity!!.id, object : CommentPresenter.AddStudyTimeCallback {
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })
    }

    //播放一组音乐
    fun playMusic(musicRes: ArrayList<String>) {}

    //停止播放
    fun stopMusic() {
        mRealm!!.executeTransaction { it ->
            val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", mAudioEntity!!.id).findFirst()
            if (rememberPlayMusicEntity != null) {
                rememberPlayMusicEntity.currentDuring = mMediaPlayer!!.currentPosition
            }
        }

        mMediaPlayer!!.stop()

        for (i in 0 until mPlayMusicCallbackList.size) {
            mPlayMusicCallbackList[i].onPlayerStop()
        }

        val intent = Intent(mMusicService, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID", mAudioEntity!!.id)
        mMusicService.startService(intent)

    }

    //暂停播放
    fun pauseMusic() {
        mMediaPlayer!!.pause()

        for (i in 0 until mPlayMusicCallbackList.size) {
            mPlayMusicCallbackList[i].onPlayerPause()
        }

        mRealm!!.executeTransaction { it ->
            val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", mAudioEntity!!.id).findFirst()
            if (rememberPlayMusicEntity != null) {
                rememberPlayMusicEntity.currentDuring = mMediaPlayer!!.currentPosition
            }
        }

        val intent = Intent(mMusicService, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID", mAudioEntity!!.id)
        mMusicService.startService(intent)
    }

    //获取音频总长度
    fun getMusicDuration(): Int {
        return mMediaPlayer!!.duration
    }

    //是否播放
    fun getCurrentMediaPlayerState(): Boolean {
        return mMediaPlayer!!.isPlaying
    }

    //释放资源
    fun onReleaseEverything() {
        if (!mDisposable!!.isDisposed) {
            mDisposable!!.dispose()
        }

        //停止播放
        stopMusic()

        //置空
        if (mMediaPlayer != null) {
            mMediaPlayer = null
        }

        mRealm!!.close()
    }

    //获取播放控制板是否可见
    fun setPlayerBarVisibilityState(isVisible: Boolean) {
        this.mPlayerBarVisibility = isVisible
        for (i in 0 until mPlayMusicCallbackList.size) {
            mPlayMusicCallbackList[i].onPlayerBarVisibleState(isVisible)
        }
    }

    //获取播放控制板是否可见
    fun getPlayerBarVisibilityState(): Boolean {
        return this.mPlayerBarVisibility
    }

    //获取音乐信息
    fun getAudioInfo(): AudioEntity? {
        return mAudioEntity
    }

    fun seekToPosition(position: Int) {
        mMediaPlayer!!.seekTo(position)
    }
}